package com.umeox.ota.ui.activity;

import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;

import com.abupdate.iot_libs.engine.trigger.CheckPeriod;
import com.abupdate.iot_libs.utils.SPFTool;
import com.abupdate.trace.Trace;
import com.umeox.ota.R;
import com.umeox.ota.SettingViewBinding;
import com.umeox.ota.data.constant.Constant;
import com.umeox.ota.mvvm.viewModel.SetViewModel;
import com.umeox.ota.ui.view.SwitchButton;
import com.umeox.ota.utils.ThemeColor;
import com.umeox.ota.utils.ViewUitls;


/**
 * @author fighter_lee
 * @date 2017/8/11.
 */
public class SetActivity extends BaseActivity<SettingViewBinding, SetViewModel> implements SwitchButton.OnCheckedChangeListener, View.OnClickListener, View.OnFocusChangeListener {
    private static final String TAG = "SetActivity";

    private static final long DEFAULT_OFFSET_HOUR = 1;
    private int preCycle;
    private ImageView toolbarBack;
    private TextView mainTitle;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void saveCheckCycle(int which) {
        preCycle = which;
        long cycle = 0;
        switch (which) {
            case 0:
                //一天+1小时，实现时间错开
                cycle = (1 * 24 + DEFAULT_OFFSET_HOUR) * 60 * 60 * 1000;
                break;
            case 1:
                cycle = (3 * 24 + DEFAULT_OFFSET_HOUR) * 60 * 60 * 1000;
                break;
            case 2:
                cycle = (7 * 24 + DEFAULT_OFFSET_HOUR) * 60 * 60 * 1000;
                break;
            default:
                cycle = CheckPeriod.getCheckPeriod();
        }
        CheckPeriod.resetPeriod((int) cycle);
    }

    @Override
    protected int genLayoutId(Bundle savedInstanceState) {
        return R.layout.activity_setting;
    }

    @Override
    public void genViewModel() {
        mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(SetViewModel.class);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mBinding.setViewmodel(mViewModel);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbarBack = findViewById(R.id.toolbar_back);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        toolbarBack = mBinding.toolbarSetting.findViewById(R.id.toolbar_back);
        toolbarBack.setImageDrawable(ViewUitls.tintDrawable(
                getResources().getDrawable(R.mipmap.ic_back),
                ColorStateList.valueOf(ThemeColor.textColorPrimary)));
        mainTitle = mBinding.toolbarSetting.findViewById(R.id.iot_main_title);
        mainTitle.setText(getString(R.string.setting));
        mBinding.setOnlyWifiSwitchButton.setChecked(SPFTool.getBoolean(Constant.SP_ONLY_WIFI_DOWNLOAD, false));
        mBinding.setUpdateSwitchButton.setChecked(SPFTool.getBoolean(Constant.SP_OTA_SILENT_UPDATE, false));

        mBinding.setOnlyWifiSwitchButton.setOnCheckedChangeListener(this);
        mBinding.setUpdateSwitchButton.setOnCheckedChangeListener(this);

        toolbarBack.setOnClickListener(this);
        mBinding.setCheckCycle.setOnClickListener(this);
        mBinding.setOnlyWifiDownload.setOnClickListener(this);
        mBinding.setAutoUpdate.setOnClickListener(this);

        toolbarBack.setOnFocusChangeListener(this);
        mBinding.setCheckCycle.setOnFocusChangeListener(this);
        mBinding.setOnlyWifiDownload.setOnFocusChangeListener(this);
        mBinding.setAutoUpdate.setOnFocusChangeListener(this);

        onFocusChange(mBinding.setAutoUpdateLine, true);

        //        if (!policyConfig.install_force || !policyConfig.download_force) {
        //            mBinding.setAutoUpdate.setVisibility(View.GONE);
        //            mBinding.setAutoUpdateLine.setVisibility(View.GONE);
        //        }
        //        if (!policyConfig.wifi) {
        //            mBinding.setOnlyWifiDownload.setVisibility(View.GONE);
        //            mBinding.setOnlyWifiDownloadLine.setVisibility(View.GONE);
        //        }
        //        if (!policyConfig.check_cycle) {
        //            mBinding.setCheckCycle.setVisibility(View.GONE);
        //            mBinding.setCheckCycleLine.setVisibility(View.GONE);
        //        }
        preCycle = parseCheckCycle();
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        Trace.d(TAG, "onCheckedChanged() " + isChecked);
        switch (view.getId()) {
            case R.id.set_only_wifi_switch_button:
                SPFTool.putBoolean(Constant.SP_ONLY_WIFI_DOWNLOAD, isChecked);
                break;

            case R.id.set_update_switch_button:
                SPFTool.putBoolean(Constant.SP_OTA_SILENT_UPDATE, isChecked);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.set_only_wifi_download:
                mBinding.setOnlyWifiSwitchButton.setChecked(!mBinding.setOnlyWifiSwitchButton.isChecked());
                break;
            case R.id.set_auto_update:
                mBinding.setUpdateSwitchButton.setChecked(!mBinding.setUpdateSwitchButton.isChecked());
                break;
            case R.id.set_check_cycle:
                preCycle = preCycle == -1 ? 0 : preCycle;
                Trace.d(TAG, "pre_cycle: " + preCycle);
                ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, R.layout.check_tv_layout, getResources().getTextArray(R.array.check_cycle));
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setTitle(R.string.set_check_cycle)
                        .setSingleChoiceItems(adapter, preCycle, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Trace.d(TAG, "onSelection() " + which);
                                if (which != preCycle && which != -1) {
                                    preCycle = which;
                                }
                            }
                        })
                        .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                            if (preCycle != -1) {
                                saveCheckCycle(preCycle);
                            }
                        }).create();
                alertDialog.show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        mBinding.setAutoUpdate.setFocusable(true);
        mBinding.setOnlyWifiDownload.setFocusable(true);
        mBinding.setCheckCycle.setFocusable(true);
        toolbarBack.setFocusable(true);
        switch (v.getId()) {
            case R.id.toolbar_back:
            case R.id.set_auto_update:
            case R.id.set_check_cycle:
            case R.id.set_only_wifi_download:
                if (hasFocus) {
                    v.setBackgroundColor(ViewUitls.darkenColor(ThemeColor.backgroundColor));
                } else {
                    v.setBackgroundColor(ThemeColor.backgroundColor);
                }
                break;
            default:
                break;
        }
    }

    private int parseCheckCycle() {
        //获取检测版本成功后保存的检测周期（单位：分钟）
        long cycle = CheckPeriod.getCheckPeriod();
        //        long cycle = 1;
        long hour = cycle / 1000 / 60 / 60;
        float v = (hour - DEFAULT_OFFSET_HOUR + 0f) / 24;
        float v1 = (hour + DEFAULT_OFFSET_HOUR + 0f) / 24;
        if (v <= 1 && 1 <= v1) {
            //一天
            return 0;
        } else if (v <= 3 && 3 <= v1) {
            //三天
            return 1;
        } else if (v <= 7 && 7 <= v1) {
            //一周
            return 2;
        }
        return -1;
    }

}
